package com.oc.mba.ui;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.umipay.android.GameParamInfo;
import net.umipay.android.UmiPaySDKManager;
import net.umipay.android.UmipayOrderInfo;
import net.umipay.android.interfaces.InitCallbackListener;
import net.umipay.android.interfaces.OrderReceiverListener;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.lurencun.android.support.ui.BaseActivity;
import com.lurencun.android.support.widget.CommonAdapter;
import com.lurencun.android.toolkit.util.ActivitySwitcher;
import com.oc.mba.AppSetting;
import com.oc.mba.R;
import com.oc.mba.entity.MenuEntity;
import com.oc.mba.http.HttpHandler;
import com.oc.mba.http.RequestParams;
import com.oc.mba.presist.Profile;
import com.oc.mba.res.MenuAdapter;
import com.oc.mba.res.MenuLoader;
import com.oc.mba.util.CommConsts;
import com.oc.mba.util.CommonUtil;
import com.oc.mba.util.GsonUtil;
import com.oc.mba.util.HttpUtil;
import com.oc.mba.util.ProfileUtil;

public class MenuActivity extends BaseActivity implements InitCallbackListener, OrderReceiverListener {
	
	private Context mContext;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		this.hideTitleBar();
		this.bindDoubleClickExit();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mContext = this;
		bind();
		Profile profile = ProfileUtil.getInstance().getProfile(mContext);
		// 没有登记设备信息
		if (!profile.isRegistered()) {
			// 网络可用, 登记设备信息
			if (CommonUtil.isNetworkAvailable(mContext)) {
				registerDevice(profile);
			}
		}
		// 初始化有米支付sdk参数
		initYoumiSDK();
	}

	/**
	 * 登记设备信息
	 * @param profile
	 */
	private void registerDevice(final Profile profile) {
		// 查询试卷返回处理Handler
		final HttpHandler paperHttpHandler = new HttpHandler(mContext, true) {
			@Override
			protected void success(String obj) {
				super.success(obj);
				try {
					Map<String, Object> map = GsonUtil.stm(obj);
					Integer result = GsonUtil.oti(map.get("Result"));
					// 操作成功
					if (result == 0) {
						Integer deviceID = GsonUtil.oti(map.get("deviceID"));
						Integer level = GsonUtil.oti(map.get("level"));
						profile.setVipLevel(level);
						profile.setDeviceID(deviceID);
						ProfileUtil.getInstance().saveProfile(mContext, profile);
						Log.d("------", "registerDevice success. deviceID=" + deviceID + ", vipLevel=" + level);
					}
					// 操作失败
					else {
						Log.d("------", "registerDevice failure. result=" + result);
					}
				} catch (Exception e) {
					Log.e("------", "registerDevice error.", e);
				}
			}

			@Override
			protected void failure(String obj) {
				super.failure(obj);
			}

		};
		
		RequestParams params = new RequestParams();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "100");
		reqMap.put("imei", profile.getImei());
		reqMap.put("androidID", profile.getAndroidID());
		params.put("req", GsonUtil.otj(reqMap));
		try {
			HttpUtil.getInstance().post(params, paperHttpHandler);
		} catch (UnsupportedEncodingException e) {
			Log.e("------", "Req100 http error.", e);
		}
	}

	/**
	 * 初始化友盟支付SDK
	 */
	private void initYoumiSDK() {
		// 初始化参数
		GameParamInfo gameParamInfo = new GameParamInfo();
		// 您的应用的AppId
		gameParamInfo.setAppId(CommConsts.APPID);
		// 您的应用的AppSecret
		gameParamInfo.setAppSecret(CommConsts.APPSECRET);

		// false 订单充值成功后是使用服务器通知 true 订单充值成功后使用客户端回调
		gameParamInfo.setSDKCallBack(false);
		// 调用sdk初始化接口
		UmiPaySDKManager.initSDK(this, gameParamInfo, this, this);
	}

	/**
	 * 
	 * 友盟支付SDK初始化成功，返回用户信息
	 * 
	 */
	@Override
	public void onInitCallback(int code, String msg) {
//		if (code == UmipaySDKStatusCode.SUCCESS) {
//			// 初始化成功后，即可正常调用充值
//			Toast.makeText(this, "初始化成功", Toast.LENGTH_SHORT).show();
//		} else if (code == UmipaySDKStatusCode.INIT_FAIL) {
//			// 初始化失败，一般在这里提醒用户网络有问题，反馈，等等问题
//			Toast.makeText(this, "初始化失败", Toast.LENGTH_SHORT).show();
//		}
	}
	
	/**
	 * 友盟支付SDK接收到服务器返回的订单信息 ！！！
	 * 注意，该返回是在非ui线程中回调，如果需要更新界面，需要手动使用主线刷新
	 */
	@Override
	public List onReceiveOrders(List list) {
		// 未处理的订单
		List<UmipayOrderInfo> newOrderList = list;
		// 已处理的订单
		List<UmipayOrderInfo> doneOrderList = new ArrayList<UmipayOrderInfo>();
		// TODO 出来服务器返回的订单信息newOrderList，并将已经处理好充值的订单返回给sdk
		// TODO sdk将已经处理完的订单通知给服务器。服务器下次将不再返回游戏客户端已经处理过的订单
		for (UmipayOrderInfo newOrder : newOrderList) {
			try {
				// TODO 对订单order进行结算
				if (newOrder.getStatus() == 1) {
					// 注意，转成毫秒需要 乘以长整型1000L
					String payTime = DateFormat.format("yyyy-MM-dd kk:mm:ss",
							newOrder.getPayTime_s() * 1000L).toString();
					final String tips = String.format("支付订单号:%s \n"
							+ "用户标记:%s \n" + "订单状态:%s \n" + "支付通道:%s \n"
							+ "获得金币:%s \n" + "金额:%s￥ \n" + "支付时间:%s \n"
							+ "自定义数据:%s \n", newOrder.getOid(),
							newOrder.getRid(), newOrder.getStatus() + "",
							newOrder.getPayType(), newOrder.getAmount() + "",
							newOrder.getRealMoney() + "", payTime,
							newOrder.getCData());
					// 在主线程更新界面
					new Handler(getMainLooper()).post(new Runnable() {
						@Override
						public void run() {
							
						}
					});
					// 添加到已处理订单列表
					doneOrderList.add(newOrder);
				}
			} catch (Exception e) {

			}
		}
		return doneOrderList;
	}
	
	private void bind() {
		GridView grid = (GridView) findViewById(R.id.menu_grid);
		CommonAdapter<MenuEntity> adapter = new MenuAdapter(this);
		final List<MenuEntity> data = new MenuLoader(this)
				.load(R.array.menu_config);
		adapter.updateDataCache(data);
		grid.setAdapter(adapter);

		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				MenuEntity menu = data.get(position);
				// 搜索
				if (menu.value == 0) {
					onSearchRequested();
				} else {
					String[] keys = new String[] { AppSetting.MENU_KEY, AppSetting.MENU_TITLE };
					Object[] vals = new Object[] { menu.value, menu.title };
					ActivitySwitcher.switchTo(MenuActivity.this, menu.nextUI, keys, vals);
				}
			}

		});
	}
}